<?php
// +----------------------------------------------------------------------
// | Exchanges
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Api\Logic;

/**
 * 用户模型业务逻辑
 *
 * @author derek <693472824@qq.com>
 */
class UserLogic extends BaseLogic {
    
    /**
     * 用户登录认证
     *
     * @param string $account   用户名
     * @param string $password  用户密码
     * @return integer 登录成功-用户ID，登录失败-错误编号
     * @author derek <693472824@qq.com>
     */
    public function login ($account, $password) {
        
        $map['account'] = (string)$account;
        
        /* 获取用户数据 */
        $user = M('User')->where($map)->find();
        
        // 用户存在并且未禁止登录
        if (is_array($user) && $user['status'] == 1) {
            
            /* 验证用户密码 */
            $user_auth_key = C('USER_AUTH_KEY');
            if (think_ucenter_md5($password, $user_auth_key) === $user['password']) {
                
                $this->updateLogin($user['user_id']);
                
                // 记录行为
                //D('Action', 'Logic')->action_log('user_login', 'user', $user['admin_id'], $user['admin_id']);
                
                /* 记录登录SESSION和COOKIES */
                $auth = array(
                        'u_id' => $user['user_id'],
                        'u_n' => $user['username'],
                        'last_login_time' => $user['last_login_time']
                );
                
                session('user_auth', $auth);
                session('user_auth_sign', data_auth_sign($auth));
                
                return $user['user_id'];
            } else {
                return - 2; // 密码错误
            }
        } else {
            return - 1; // 用户不存在或被禁用
        }
    }

    /**
     * 更新用户登录信息
     *
     * @param integer $uid
     *            用户ID
     * @author derek <693472824@qq.com>
     */
    protected function updateLogin ($uid){
        
        $data = array(
                'user_id' => $uid,
                'last_login_time' => NOW_TIME,
                'last_login_ip' => get_client_ip(1)
        );
        M('User')->save($data);
    }

    /**
     * 用户退出
     * @author derek <693472824@qq.com>
     */
    public function logout () {
        
        $userID = self::is_login();
        session('user_auth', null);
        session('user_auth_sign', null);
    }

    /**
     * 判断用户是否登录
     *
     * @author derek <693472824@qq.com>
     */
    public static function is_login () {
        
        $user = session('user_auth');
        if (empty($user)) {
            return 0;
        } else {
            return session('user_auth_sign') == data_auth_sign($user) ? $user['u_id'] : 0;
        }
        
    }

    /**
     * 根据user_id获取账号
     *
     * @param integer $uid 用户ID
     * @author derek <693472824@qq.com>
     */
    public static function getAccount ($uid) {
        
        if(empty($uid) || !is_numeric($uid)){
            $uid = self::is_login();
        }
        
        $map['user_id'] = $uid;
        $account = M('User')->where($map)->getField('account');
        $account = empty($account) ? '' : $account;
        
        return $account;
    }
    
    /**
     * 领取优惠券
     * @param category 1:注册券；2：邀请好友得到的优惠券；3：活动券；
     * @param value 优惠券金额 支持两种表示方式：满减（100-20）、定额（20）
     * @param random category为3时有效，活动码
     */
    public function coupon($category='', $value='', $random='', $userID = ''){
        
        if(is_numeric($value)){
            $minimum = '0';
            $money = $value;
        }else if(strpos($value, '-')){
            list($minimum, $money) = explode('-', $value);
        }
        
        $userID = empty($userID) ? UserLogic::is_login() : $userID;
        $data['user_id'] = $userID;
        
        //邀请好友注册后领取的优惠券有优惠码
        if($category == '2'){
            $prefix = \Org\Util\String::randString(4,1);
            $suffix = \Org\Util\String::randString(4,1);
            $code = $prefix.$suffix;
            $data['code'] = $code;
        }else{
            $data['code'] = $random;
        }
        
        //1：注册券；2：邀请好友注册成功后券；3：活动券；
        $data['category'] = $category;
        $data['minimum'] = $minimum;
        $data['money'] = $money;
        $data['create_time'] = NOW_TIME;
        
        //优惠券有效期，单位：天
        $period = C('COUPON_VALIDITY_PERIOD');
        $period = empty($period) ? 0 : NOW_TIME + $period * 24 * 3600;
        $data['deadline'] = $period;
        
        $data['status'] = '1';      //1：未使用；2:已使用；3：过期
        
        return M('UserCoupon')->add($data);
        
    }
    
    /**
     * 根据订单金额计算用户可使用的最优的优惠券
     */
    public function couponSolution($total='0', $couponID=''){
        
        $userID = self::is_login();
        $couponModel = M('UserCoupon');
        
        $map['user_id'] = $userID;
        $map['status'] = '1';           //1：可用；2：已用；3：已过期
        $map['deadline'] = array('GT',NOW_TIME);
        
        //不为空时，表示用户指定使用优惠券
        if(!empty($couponID)){
            $map['coupon_id'] = $couponID;
            $coupon = $couponModel->where($map)->find();
        }else{
            
            //$map['_string'] = ' (minimum=0 AND '.$total.'>money) OR (minimum>0 AND '.$total.'>minimum) ';      
            //$coupon = $couponModel->where($map)->order('deadline, money DESC')->find();
        }
        
        return $coupon;
    }
    
}

?>